package com.xywy.me;

import java.util.Calendar;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONObject;

import android.R.integer;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xywy.R;
import com.xywy.common.BaseActivity;
import com.xywy.common.constants.ConstantValue;
import com.xywy.common.constants.ResultCode;
import com.xywy.common.net.AsyncHttpClient;
import com.xywy.common.net.OnResultListenerAdapter;
import com.xywy.common.net.Parser;
import com.xywy.common.util.CalendarUtil;
import com.xywy.common.util.FileUtil;
import com.xywy.common.util.MLog;
import com.xywy.common.util.StringUtils;
import com.xywy.common.widget.MyDialog;
import com.xywy.common.widget.MyProgress;
import com.xywy.common.widget.TitleBar2;
import com.xywy.me.bean.Jtcy;
import com.xywy.me.bean.User;
import com.xywy.me.bean.UserKeeper;
import com.xywy.start.widget.wheel.ArrayWheelAdapter;
import com.xywy.start.widget.wheel.OnWheelChangedListener;
import com.xywy.start.widget.wheel.WheelView;

/**
 * 我 - 个人资料 -修改 头像/名字/姓别/身高/体重/生日
 * 
 * @author xiaogd
 * 
 */
public class InforUpdateActivity extends BaseActivity {
	private static final String TAG = "InforActivity";
	private RelativeLayout rlBack;
	private TextView tvTitle;
	private TextView tvGo;
	private RelativeLayout name;
	private RelativeLayout male, female;
	private RelativeLayout weight;
	private RelativeLayout height;
	private LinearLayout birth;

	private EditText etName;
	private EditText etHeight;
	private EditText etWeight;

	private Context mContext;
	private ImageView maleCheck, feMaleCheck;

	private int item = 0;

	String[] yearArrayString = null;
	String[] dayArrayString = null;
	String[] monthArrayString = null;
	Calendar c = null;
	String dateStr = null;
	private WheelView yearWV;
	private WheelView monthWV;
	private WheelView dayWV;
	int year;
	int month;
	
	private User current_user;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 设置为全屏
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.me_infor_update);

		this.preInit();
		this.initView();
		this.loadData();
		this.setListener();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();

	}

//	Jtcy jtcy = null;
//	private SharedPreferences sp;
//	private String userid;

	@Override
	public void preInit() {
		mContext = this.context;
		myProgress = new MyProgress(this, 10);

		Intent intent = this.getIntent();
		item = intent.getIntExtra("item", 0);
		current_user = UserKeeper.getCurrentUser(this);
		// jtcy = (Jtcy)intent.getSerializableExtra("jtcy");
//		jtcy = UserKeeper.getCurrentUser();
//		sp = getSharedPreferences("config", Context.MODE_PRIVATE);
//		userid = sp.getString("userid", "");
		// initBirthday();
	}

	private void initBirthday() {
		// TODO Auto-generated method stub
		yearArrayString = getYEARArray(1900, 103);
		monthArrayString = getDayArray(12);

		// 获取当前系统时间
		c = Calendar.getInstance();

		yearWV = (WheelView) findViewById(R.id.time_year);
		monthWV = (WheelView) findViewById(R.id.time_month);
		dayWV = (WheelView) findViewById(R.id.time_day);

		// 设置每个滚轮的行数
		yearWV.setVisibleItems(7);
		monthWV.setVisibleItems(7);
		dayWV.setVisibleItems(7);

		yearWV.setCyclic(true);
		monthWV.setCyclic(true);
		dayWV.setCyclic(true);
		setData();
	}

	@Override
	public void initView() {
		// title
		TitleBar2 titleBar = (TitleBar2) findViewById(R.id.me_infor_update_title_bar);
		rlBack = titleBar.getRlBack();
		tvTitle = titleBar.getTitle();
		TextView tvBack = titleBar.getTvBack();
		tvGo = titleBar.getGo();
		tvBack.setText(getString(R.string.me_infor_title));
		tvGo.setText(getString(R.string.common_save));

		// 名字
		name = (RelativeLayout) this.findViewById(R.id.rl_me_infor_update_name);
		// 姓别 (male + famale)
		male = (RelativeLayout) this.findViewById(R.id.rl_me_infor_update_male);
		female = (RelativeLayout) this
				.findViewById(R.id.rl_me_infor_update_female);

		maleCheck = (ImageView) this.findViewById(R.id.iv_me_infor_update_male);
		feMaleCheck = (ImageView) this
				.findViewById(R.id.iv_me_infor_update_female);

		height = (RelativeLayout) this
				.findViewById(R.id.rl_me_infor_update_height);
		weight = (RelativeLayout) this
				.findViewById(R.id.rl_me_infor_update_weight);
		birth = (LinearLayout) this
				.findViewById(R.id.rl_me_infor_update_birthday);

		etName = (EditText) findViewById(R.id.et_me_infor_update_name);
		etHeight = (EditText) findViewById(R.id.et_me_infor_update_height);
		etWeight = (EditText) findViewById(R.id.et_me_infor_update_weight);
	}

	int sexStr = 1;

	@Override
	public void loadData() {
		// 预加载数据
		MLog.i(TAG, "成员参数是=update========：" + current_user.toString());

		clearItem(); // 隐藏item
		switch (item) {
		case ConstantValue.NAME:
			tvTitle.setText(getString(R.string.me_infor_name));
			name.setVisibility(View.VISIBLE);
			etName.setText(current_user.getAccountstr());
			break;
		case ConstantValue.SEX:
			tvTitle.setText(getString(R.string.me_infor_sex));
			male.setVisibility(View.VISIBLE);
			female.setVisibility(View.VISIBLE);
			if (current_user.getSex() == null)
				current_user.setSex("男");
			if (current_user.getSex().equals("男")) {
				sexStr = 1;
				maleCheck.setVisibility(View.VISIBLE);
				feMaleCheck.setVisibility(View.INVISIBLE);
			} else if (current_user.getSex().equals("女")) {
				sexStr = 2;
				maleCheck.setVisibility(View.INVISIBLE);
				feMaleCheck.setVisibility(View.VISIBLE);
			}
			break;
		case ConstantValue.HEIGHT:
			tvTitle.setText(getString(R.string.me_infor_height));
			height.setVisibility(View.VISIBLE);
			etHeight.setText(current_user.getHeight());
			break;
		case ConstantValue.WEIGHT:
			tvTitle.setText(getString(R.string.me_infor_weight));
			weight.setVisibility(View.VISIBLE);
//			etWeight.setText(jtcy.getWeight());
			break;
		case ConstantValue.BIRTH:
			tvTitle.setText(getString(R.string.me_infor_birthday));
			birth.setVisibility(View.VISIBLE);
			initBirthday();
			break;

		}
	}

	/**
	 * 点击事件
	 * 
	 * @param view
	 */

	public void onClickUpdate(View view) {
		switch (view.getId()) {
		case R.id.rl_me_infor_update_male:
			maleCheck.setVisibility(View.VISIBLE);
			feMaleCheck.setVisibility(View.INVISIBLE);
			sexStr = 1;
			break;
		case R.id.rl_me_infor_update_female:
			maleCheck.setVisibility(View.INVISIBLE);
			feMaleCheck.setVisibility(View.VISIBLE);
			sexStr = 2;
			break;
		case R.id.iv_me_name_cancel:
			etName.setText("");
			break;
		case R.id.iv_me_height_cancel:
			etHeight.setText("");
			break;
		case R.id.iv_me_weight_cancel:
			etWeight.setText("");
			break;
		}
	}

	/**
	 * 隐藏item
	 * 
	 */
	private void clearItem() {
		name.setVisibility(View.GONE);
		male.setVisibility(View.GONE);
		female.setVisibility(View.GONE);
		height.setVisibility(View.GONE);
		weight.setVisibility(View.GONE);
		birth.setVisibility(View.GONE);
	}

	/**
	 * 点击保存获取值
	 */
	private void setListener() {
		tvGo.setOnClickListener(onGoClickListener);
		rlBack.setOnClickListener(onBackListener);
	}

	View.OnClickListener onGoClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View view) {
			// 发送网络请求
			switch (item) {
			case ConstantValue.NAME:
				String nameStr = etName.getText().toString().trim();
				if (nameStr == null || "".equals(nameStr)) {
					Toast.makeText(InforUpdateActivity.this, "请输入姓名",
							Toast.LENGTH_SHORT).show();
					return;
				} else if (StringUtils.isNull(nameStr) || 2 > nameStr.length()
						|| 16 < nameStr.length()) {
					Toast.makeText(InforUpdateActivity.this, "请输入2~8中文字",
							Toast.LENGTH_SHORT).show();
					return;
				} else {
					if (!hasCrossRisk(nameStr)) {
						Toast.makeText(InforUpdateActivity.this, "姓名不能包含特殊字符",
								Toast.LENGTH_SHORT).show();
						return;
					}
				}
				break;

			default:
				break;
			}
			final MyDialog myDialog = new MyDialog(mContext,
					R.style.MyDialogStyle);
			myDialog.show();
			myDialog.setContentView(R.layout.mydialog_twobutton_layout);
			TextView mydialog_twobutton_layout_content_textView = (TextView) myDialog
					.findViewById(R.id.mydialog_twobutton_layout_content_textView);
			mydialog_twobutton_layout_content_textView
					.setText("为了获得精准的服务，请确保资料的真实。是否确定修改？");
			TextView leftButton = (TextView) myDialog
					.findViewById(R.id.mydialog_twobutton_layout_left_button);
			leftButton.setText("取消");
			myDialog.findViewById(R.id.mydialog_twobutton_layout_left_button)
					.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							myDialog.dismiss();
						}
					});

			myDialog.findViewById(R.id.mydialog_twobutton_layout_right_button)
					.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							// TODO Auto-generated method stub
							myDialog.dismiss();
							sendMsg();
						}

					});

		}
	};

	View.OnClickListener onBackListener = new View.OnClickListener() {
		@Override
		public void onClick(View view) {
			// 返回
			back();
		}
	};

	MyProgress myProgress;
	JSONObject msgBack = null;
	/**
	 * 返回
	 */
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			MLog.i(TAG, "back:" + msg.obj + "resuletCode:" + msg.arg1);
			myProgress.stop();
			try {
				msgBack = new JSONObject(msg.obj.toString());
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (msg.arg1 == ResultCode.SUCCESS) {
				switch (item) {
				case ConstantValue.NAME:
					current_user.setAccountstr(etName.getText().toString());
					break;
				case ConstantValue.SEX:
					String sexUpdateback = "男";
					if (sexStr == 2) {
						sexUpdateback = "女";
					}
					current_user.setSex(sexUpdateback);
					break;
				case ConstantValue.HEIGHT:
					current_user.setHeight(etHeight.getText().toString());
					break;
				case ConstantValue.WEIGHT:
//					jtcy.setWeight(etWeight.getText().toString());
					break;
				case ConstantValue.BIRTH:
					if (dateStr != null)
						current_user.setBirthday(dateStr);
					break;

				default:
					break;
				}
				UserKeeper.saveUser(current_user, InforUpdateActivity.this);
//				UserKeeper.setCurrentUser(jtcy);
//				FileUtil.saveCurrentUser(userid + "mainaccount", jtcy);
				finish();
			} else {
				if (msgBack == null)
					return;
				Toast.makeText(mContext, msgBack.optString("error"),
						Toast.LENGTH_LONG).show();
			}
		}
	};

	// 封装Parser参数
	private Parser paramsParser;
	// 封装httpclient参数
	private HashMap<String, Object> params;
	// 异步加载
	private AsyncHttpClient asyncHttpClient;

	// 处理网络请求 修改個人信息
	public void sendMsg() {
		if (ConstantValue.HEIGHT == item) {
			if (etHeight.getText().toString().trim() != null) {

				if ("".equals(etHeight.getText().toString())
						|| StringUtils.isNull(etHeight.getText().toString())) {
					Toast.makeText(this, "身高不能为空！", Toast.LENGTH_SHORT).show();
					return;

				}
				int height = Integer.parseInt(etHeight.getText().toString());
				if (height < 120 || height > 230) {
					Toast.makeText(this, "身高在120~230之间", Toast.LENGTH_SHORT)
							.show();
					return;
				}
			}
		}
		myProgress.start();
		paramsParser = new Parser();

		// 封装参数
		params = new HashMap<String, Object>();

		// 请求路径
		paramsParser.action = getString(R.string.update_user_infor);
		// 请求方式
		paramsParser.request = "post";
		// 请求参数
//		SharedPreferences sp = context.getSharedPreferences("config",
//				Context.MODE_PRIVATE);
//		String userid = sp.getString("userid", "");

		params.put("userid", current_user.getUserid());
		params.put("accountstr", etName.getText().toString());
		params.put("sex", sexStr);
		params.put("height", etHeight.getText().toString());
		params.put("weight", etWeight.getText().toString());
		if (ConstantValue.BIRTH == item) {

		} else {
			dateStr = current_user.getBirthday();
			if (dateStr == null) {
				Calendar c = Calendar.getInstance();
				createDate(c.get(Calendar.YEAR) + "", c.get(Calendar.MONTH)
						+ "", c.get(Calendar.DAY_OF_MONTH) + "");
				current_user.setBirthday(dateStr);
			}
		}
		String dateStr2 = CalendarUtil.getTimstamp(dateStr);
		System.out.println(dateStr);
		Log.e("date___str", dateStr2);
		params.put("birthday", dateStr2);

		params.put("keyword", "edit");

		paramsParser.map = params;
		// 传递上下文
		paramsParser.context = this.context;

		asyncHttpClient = AsyncHttpClient.getInstance();
		asyncHttpClient.exeute(paramsParser, onResultListenerAdapter);
	}

	OnResultListenerAdapter onResultListenerAdapter = new OnResultListenerAdapter() {
		@Override
		public <T extends Parser> void onSuccess(T resultParser, int resultCode) {
			super.onSuccess(resultParser, resultCode);
			Message message = Message.obtain();
			message.arg1 = resultCode;
			message.obj = resultParser.back;
			handler.sendMessage(message);
		}
	};

	@Override
	public void onBackPressed() {
		back();
		super.onBackPressed();
	}

	/**
	 * 返回处理
	 */
	public void back() {
		// Intent intent =new Intent(this,InforActivity.class);
		// intent.putExtra("jtcy",jtcy);
		// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		// startActivity(intent);
		this.finish();
	}

	/**
	 * 给滚轮提供数据
	 */
	private void setData() {
		// 给滚轮提供数据
		yearWV.setAdapter(new ArrayWheelAdapter<String>(yearArrayString));
		monthWV.setAdapter(new ArrayWheelAdapter<String>(monthArrayString));

		yearWV.addChangingListener(new OnWheelChangedListener() {
			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// 获取年和月
				year = Integer.parseInt(yearArrayString[yearWV.getCurrentItem()]);
				month = Integer.parseInt(monthArrayString[monthWV
						.getCurrentItem()]);
				// 根据年和月生成天数数组
				dayArrayString = getDayArray(getDay(year, month));
				// 给天数的滚轮设置数据
				dayWV.setAdapter(new ArrayWheelAdapter<String>(dayArrayString));
				// 防止数组越界
				if (dayWV.getCurrentItem() >= dayArrayString.length) {
					dayWV.setCurrentItem(dayArrayString.length - 1);
				}
				// 显示的时间
				showDate();
			}
		});

		// 当月变化时显示的时间
		monthWV.addChangingListener(new OnWheelChangedListener() {

			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// 获取年和月
				year = Integer.parseInt(yearArrayString[yearWV.getCurrentItem()]);
				month = Integer.parseInt(monthArrayString[monthWV
						.getCurrentItem()]);
				// 根据年和月生成天数数组
				dayArrayString = getDayArray(getDay(year, month));
				// 给天数的滚轮设置数据
				dayWV.setAdapter(new ArrayWheelAdapter<String>(dayArrayString));
				// 防止数组越界
				if (dayWV.getCurrentItem() >= dayArrayString.length) {
					dayWV.setCurrentItem(dayArrayString.length - 1);
				}
				// 显示的时间
				showDate();
			}
		});

		// 当天变化时，显示的时间
		dayWV.addChangingListener(new OnWheelChangedListener() {
			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				showDate();
			}
		});

		// 把当前系统时间显示为滚轮默认时间
		setOriTime();
	}

	// 设定初始时间
	void setOriTime() {
		yearWV.setCurrentItem(getNumData(1992 + "",// c.get(Calendar.YEAR)
				yearArrayString));
		monthWV.setCurrentItem(getNumData(c.get(Calendar.MONTH) + 1 + "",
				monthArrayString) + 0);

		dayArrayString = getDayArray(getDay(year, month));
		dayWV.setAdapter(new ArrayWheelAdapter<String>(dayArrayString));
		dayWV.setCurrentItem(getNumData(c.get(Calendar.DAY_OF_MONTH) + "",
				dayArrayString));

		// 初始化显示的时间
		showDate();
	}

	// 显示时间
	void showDate() {
		createDate(yearArrayString[yearWV.getCurrentItem()],
				monthArrayString[monthWV.getCurrentItem()],
				dayArrayString[dayWV.getCurrentItem()]);
	}

	// 生成时间
	void createDate(String year, String month, String day) {
		dateStr = year + "-" + month + "-" + day;
	}

	// 在数组Array[]中找出字符串s的位置
	int getNumData(String s, String[] Array) {
		int num = 0;
		for (int i = 0; i < Array.length; i++) {
			if (s.equals(Array[i])) {
				num = i;
				break;
			}
		}
		return num;
	}

	// 根据当前年份和月份判断这个月的天数
	public int getDay(int year, int month) {
		int day;
		if (year % 4 == 0 && year % 100 != 0) { // 闰年
			if (month == 1 || month == 3 || month == 5 || month == 7
					|| month == 8 || month == 10 || month == 12) {
				day = 31;
			} else if (month == 2) {
				day = 29;
			} else {
				day = 30;
			}
		} else { // 平年
			if (month == 1 || month == 3 || month == 5 || month == 7
					|| month == 8 || month == 10 || month == 12) {
				day = 31;
			} else if (month == 2) {
				day = 28;
			} else {
				day = 30;
			}
		}
		return day;
	}

	// 根据数字生成一个字符串数组
	public String[] getDayArray(int day) {
		String[] dayArr = new String[day];
		for (int i = 0; i < day; i++) {
			dayArr[i] = i + 1 + "";
		}
		return dayArr;
	}

	// 根据数字生成一个字符串数组
	public String[] getHMArray(int day) {
		String[] dayArr = new String[day];
		for (int i = 0; i < day; i++) {
			dayArr[i] = i + "";
		}
		return dayArr;
	}

	// 根据初始值start和step得到一个字符数组，自start起至start+step-1
	public String[] getYEARArray(int start, int step) {
		String[] dayArr = new String[step];
		for (int i = 0; i < step; i++) {
			dayArr[i] = start + i + "";
		}
		return dayArr;
	}

	/**
	 * 检查输入的数据中是否有特殊字符
	 * 
	 * @param qString
	 *            要检查的数据
	 * @param regx
	 *            特殊字符正则表达式
	 * @return boolean 如果包含正则表达式<code>regx</code>中定义的特殊字符，返回true； 否则返回false
	 */
	public static boolean hasCrossRisk(String str) {
		String regx = "^[a-zA-Z0-9_\u4e00-\u9fa5]+$";
		Pattern p = Pattern.compile(regx);
		if (str != null)
			return p.matches(regx, str);
		else
			return false;
	}

}
